import router from './router'
import { constantRoutes } from './router'

import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// import getPageTitle from '@/utils/get-page-title'
import { luyou } from '@/router/index'
NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '404']
// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      // next函数很特殊 当next()时可以触发路由后置守卫，但是里面有参数时没法触发路由后置守卫需要手动关闭进度条
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        // 调用方法存储获取的用户数据，然后存到vuex/user.js中
        await store.dispatch('user/getData')
        // console.log(luyou)
        // console.log(store.state.user.userdata.roles.menus)
        const filterRoutes = luyou.filter(item => {
          return store.state.user.userdata.roles.menus.includes(item.name)
        })
        store.commit('user/updongRouter', [...constantRoutes, ...filterRoutes])
        // constantRoutes
        // console.log(filterRoutes)
        // 刷新会报404解决办法
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        // 解决刷新白屏
        next(to.path)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
// 路由后置守卫
router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})
